package dao;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import bean.PostBean;
import bean.UserBean;

//TODO
/**
 * Class responsible for the operations of PostDAO
 * @author Otavio Lima, Laura Dutra
 *
 */
public class PostDAO implements DAO<PostBean> {
 
	private static final File DB = new File("./PostDB.xml");
	private static PostDAO instance;

	/**
	 * Constructor 
	 */
	private PostDAO(){

	}


	/**
	 * Singleton 
	 * @return instance of PostDAO
	 */

	public static synchronized PostDAO getInstance(){
		if(instance == null)
			instance = new PostDAO();

		return instance;
	}
	/**
	 * @see dao.DAO#list()
	 */

	public List<PostBean> list() {
		XMLDecoder decoder = null;
		List<PostBean> list = null;
		try {
			decoder = new XMLDecoder(new BufferedInputStream(
					new FileInputStream(DB)));
			list = (List<PostBean>) decoder.readObject();
			return list;
		} catch (Exception e1) {
			return new ArrayList<PostBean>();
		} finally {
			if (decoder != null) {
				decoder.close();
			}
		}
	}

	/**
	 * @see dao.DAO#delete(dao.T)
	 */
	public boolean delete(PostBean bean) {
		List<PostBean> posts = list();
		Iterator<PostBean> it = posts.iterator();
		PostBean post;
		while (it.hasNext()) {
			post = it.next();
			if (bean.equals(post)) {
				posts.remove(post);
				return writeList(posts);
			}

		}
		return false;
	}


	/**
	 * @see dao.DAO#update(dao.T)
	 */
	public boolean update(PostBean bean) {
		List<PostBean> posts = list();
		Iterator<PostBean> it = posts.iterator();
		PostBean post;
		while (it.hasNext()) {
			post = it.next();
			if (bean.equals(post)) {
				posts.remove(post);
				posts.add(bean);
				return writeList(posts);
			}

		}
		return false;
	}


	/**
	 * @see dao.DAO#save(dao.T)
	 */
	public boolean save(PostBean bean) {
		List<PostBean> list = list();
		list.add(bean);
		return writeList(list);
	}

	/**
	 * @see dao.DAO#contains(dao.T)
	 */
	public boolean contains(PostBean bean) {
		List<PostBean> posts = list();
		Iterator<PostBean> it = posts.iterator();
		PostBean post;
		while (it.hasNext()) {
			post = it.next();
			if (bean.equals(post)) {
				return true;

			}

		}
		return false;
	}

	/**
	 * Writes a list of the PostBean in db 
	 * @param list
	 * @return boolean
	 */
	public boolean writeList(List<PostBean> list) {
		XMLEncoder encoder = null;
		try {
			encoder = new XMLEncoder(new BufferedOutputStream(
					new FileOutputStream(DB)));
			encoder.writeObject(list);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (encoder != null) {
				encoder.close();
			}
		}
		return false;
	}

}

